var Events = require('ym-Events')
//微信模块的功能调用
let isRecordding = false;
let isPlayRecord = false; //是否正在播放录音
let isChange = false;
let wxAudio = null;
let recordFiles = [];  //所有需要播放的录音都先来这里存着，然后一个个播放
let onShowTime = 0
let setTime;
var btnLogin = null
cc.Class({
    extends: require('wy-PlatformBase'),
    init() {
        this._super();
        this.os = 'wechat'
        this.isWechat = true
        onShowTime = Date.now();
        var obj = typeof (window.wx);
        if (obj != 'undefined') {
            var option = wx.getLaunchOptionsSync();
            this.wxLaunchQuery = option.query;
            this.wxReferrerInfo = option.referrerInfo
            console.log('监听onShow，触发时调起检测新版本');
            wx.onShow(this._onShow.bind(this));
            wx.onHide(this._onHide.bind(this));
            wx.onNetworkStatusChange(this.changeNetwork.bind(this));
            setTimeout(() => {
                console.log('开始检测新版本');
                this.checkNewVersion();
            }, 1000);
            wx.onShareAppMessage(() => {
                let query;
                let msg;
                msg = { parentId: global.Data._id }
                query = Object.keys(msg).map((key) => { return key + '=' + msg[key]; }).join("&");
                return {
                    title: '[新消息]还记得记忆中的雷电吗，快来跟我一起爽快射击吧。',
                    imageUrl: 'https://oss.073c.com/planewar/fengxiangtu2.png',
                    query: query,
                }
            });
            wx.showShareMenu();
            if (wx.setKeepScreenOn) {
                wx.setKeepScreenOn({ keepScreenOn: true });
            }
        } else {
            this.wxLaunchQuery = '';
        }

        this._videoError = function(){
            cc.sys.localStorage.setItem('lastRewardTime',Date.now());
            cc.sys.localStorage.setItem('lastHasVideo',2);
            console.log('videoAd onError:', e);
        }
    },

    getLaunchOption() {
        return this.wxLaunchQuery;
    },
    getReferrerInfo() {
        return this.wxReferrerInfo;
    },

    clearOption() {
        this.wxLaunchQuery = null;
        this.wxReferrerInfo = null;
    },

    destroyLoginButton() {
        if (!!btnLogin) {
            btnLogin.destroy();
            btnLogin = null;
        }
    },

    hideLoading() {
        if (!CC_DEV) wx.hideLoading();
    },

    //微信自动登录
    login(cb) {
        console.log('这里是wechat login');
        var self = this;
        let clickOne = true;
        wx.login({
            success: function (res) {
                var systemInfo = wx.getSystemInfoSync();
                if (!!btnLogin) { btnLogin.destroy() }
                console.log('开始创建btnLogin');
                btnLogin = wx.createUserInfoButton({
                    type: "image",
                    image: "https://oss.073c.com/planewar/wechatlogin.png",
                    style: { left: 0, top: 0, width: systemInfo.screenWidth, height: systemInfo.screenHeight },
                    withCredentials: true
                });
                btnLogin.onTap(function (data) {
                    if (!data.iv) return;
                    let obj = { code: res.code, iv: data.iv, encryptedData: data.encryptedData, signature: data.signature};
                    self.destroyLoginButton();
                    clickOne && cb(obj);
                    clickOne = false
                }.bind(this));
                console.log('开始调用btnLogin.show');
                btnLogin.show();
            }.bind(this),
            fail:function(){
                self.login(cb)
            }
        })
    },

    login(cb) {
        console.log('这里是wechat login');
        var self = this;
        let clickOne = true;
        wx.login({
            success: function (res) {
                clickOne && cb(res);
                clickOne = false
            }.bind(this),
            fail:function(){
                self.login(cb)
            }
        })
    },
    getUserInfo(x,y,cb){
        let clickOne = true;
        var systemInfo = wx.getSystemInfoSync();
        if (!!btnLogin) { btnLogin.destroy() }
        console.log('开始创建btnLogin');
        var self = this;

        btnLogin = wx.createUserInfoButton({
            type: "image",
            image: "https://oss.073c.com/planewar/wechatlogin.png",
            style: { left: 0, top: 0, width: systemInfo.screenWidth, height: systemInfo.screenHeight },
            withCredentials: true
        });
        btnLogin.onTap(function (data) {
            self.destroyLoginButton();
            
            if (!data.iv){
                clickOne && cb(null);
                clickOne = false
                return;
            }
            let obj = {iv: data.iv, encryptedData: data.encryptedData, signature: data.signature};
            
            clickOne && cb(obj);
            clickOne = false
        }.bind(this));
        console.log('开始调用btnLogin.show');
        btnLogin.show();
    },

    //获取地理位置  回掉函数中的res.latitude,res.longitude为经纬度
    getLocation(cb) {
        if (!CC_DEV) {
            wx.getLocation({
                success: (res) => {
                    cb(res);
                    cc.sys.localStorage.setItem("getLocation", 1);
                },
                fail: () => {
                    cc.sys.localStorage.setItem("getLocation", 0);
                    cb({ latitude: 999, longitude: 999 });
                }
            });
        } else {
            setTimeout(() => {
                cb({ latitude: 100, longitude: 100 })
            }, 10);
        }
    },
    //转发
    //开始录音
    startRecord(userID) {
        if (isRecordding) { return; }
        cc.log('开始录音');
        isRecordding = true;
        cc.audioEngine.setMusicVolume(0);
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.start({
            duration: 15000,
            sampleRate: 44100,
            encodeBitRate: 64000,
            format: 'mp3'
        });
        RecorderManager.onError((res) => {
            console.log('录音错误', res);
        });
        RecorderManager.onStop((data) => {
            cc.log('录音结束');
            isRecordding = false;
            if (!isPlayRecord) cc.audioEngine.setMusicVolume(1);
            Events.emit('stopRecord');
            let tempFilePath = data.tempFilePath;
            let fileName = `${userID}_${new Date().getTime()}`;
            cc.log('开始上传录音', tempFilePath);
            wx.uploadFile({
                url: Config.uploadRecordUrl,
                filePath: tempFilePath,
                name: fileName,
                formData: { fileName: fileName + '.mp3' },
                fail: (res) => {
                    console.log('MP3文件上传失败', res);
                },
                success: (res) => {
                    console.log('MP3文件上传成功', res);
                    var msg = { r: 'roomBroadcast', e: 'roomBroadcast', userID: userID, fileName: fileName + '.mp3' }
                    WS.send(msg);
                }
            });
        });
        Events.emit('startRecord');
    },
    triggerGC() {
        wx.triggerGC();
    },
    destroyClubBtn() {
        if (CC_WECHATGAME) {
            if (!!this.GameClubButton) this.GameClubButton.destroy();
        }
    },
    copyString(str) {
        if (CC_WECHATGAME) {
            wx.setClipboardData({ data: str });
        }
    },

    openSetting(cb) {
        if (CC_WECHATGAME) {
            wx.openSetting({
                success(res) { cb(res); }
            });
        }
    },

    vibrateLong() {
        if (CC_WECHATGAME) {
            wx.vibrateLong();
        }
    },

    createClubBtn() {
        if (CC_WECHATGAME) {
            var systemInfo = wx.getSystemInfoSync();
            var left = systemInfo.screenWidth * 0.9;
            var top = systemInfo.screenHeight * 0.86;
            var wh = systemInfo.screenHeight * 0.1;
            var obj = {
                type: 'image', icon: 'green',
                style: { left: left, top: top, width: wh, height: wh }
            }
            if (!!wx.createGameClubButton) {
                this.GameClubButton = wx.createGameClubButton(obj);
                this.GameClubButton.show();
            }
        }
    },

    //停止录音
    stopRecord() {
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.stop();
    },
    //播放网络录音
    playRecord(userID, fileName) {
        let url = Config.readRecordRootUrl + fileName;
        let recordFile = { userID: userID, fileName: fileName };
        wxAudio = wx.createInnerAudioContext();
        wxAudio.src = url;
        wxAudio.loop = false;
        wxAudio.onPlay(() => {
            console.log('播放录音');
            cc.audioEngine.setMusicVolume(0);
            Events.emit('playRecordStart', recordFile);
        });
        wxAudio.onEnded(() => {
            console.log('播放录音结束');
            Events.emit('playRecordEnd', recordFile);
            if (!isRecordding) cc.audioEngine.setMusicVolume(1);
        });
        wxAudio.onError((res) => {
            console.log('播放错误', res);
            Events.emit('playRecordEnd', recordFile);
            if (!isRecordding) cc.audioEngine.setMusicVolume(1);
        });
        wxAudio.play();
    },
    playOneRecord() {
        isPlayRecord = true;
        let recordFile = recordFiles.shift();
        let url = Config.readRecordRootUrl + recordFile.fileName;
        wxAudio = wx.createInnerAudioContext();
        wxAudio.src = url;
        wxAudio.loop = false;
        wxAudio.onPlay(() => {
            console.log('播放录音');
            cc.audioEngine.setMusicVolume(0);
            Events.emit('playRecordStart', recordFile);
        });
        wxAudio.onEnded(() => {
            console.log('播放录音结束');
            Events.emit('playRecordEnd', recordFile);
            if (!isRecordding) {
                cc.audioEngine.setMusicVolume(1);
            }
            if (recordFiles.length > 0) {
                this.playOneRecord();
            } else {
                isPlayRecord = false;
            }
        });
        wxAudio.onError((res) => {
            console.log('播放错误', res);
            Events.emit('playRecordEnd', recordFile);
            if (!isRecordding) {
                cc.audioEngine.setMusicVolume(1);
            }
            if (recordFiles.length > 0) {
                this.playOneRecord();
            } else {
                isPlayRecord = false;
            }
        });
        wxAudio.play();
    },
    //分享 type:  1   2   3   4
    // 1 新旧四个角色站在一起
    // 2 男女两个角色靠在一起，害羞脸红，面对面，中间有个比心。
    // 3 一个角色穿着皇帝的衣服。
    // 4 两个角色左右各一个，中间一个礼包。两个角色都抱着礼包。
    // 5 角色背着书包 笑
    // 6 角色跪在地上 哭
    // 7 角色在一堆金币中抛金币
    share(title, queryObj, successCallBack, type = 1) {
        let query = Object.keys(queryObj).map((key) => { return key + '=' + queryObj[key]; }).join("&");
        console.log('分享的参数', query);
        wx.shareAppMessage({
            title: title,
            imageUrl: 'https://oss.073c.com/planewar/fengxiangtu.png',
            query: query,
            success: () => {
                successCallBack();
                global.EJMgr.showToast('分享成功！')
            },
            fail: () => {
                global.EJMgr.showToast('取消分享!')
            }
        });
    },
    //游戏退出
    exit() {
        wx.exitMiniProgram({});
    },
    //游戏截图
    screenshot(argObj, cb) {
        var system = wx.getSystemInfoSync();
        var width = system.screenWidth * system.pixelRatio;
        var height = system.screenHeight * system.pixelRatio;
        var w = height * 1.25;
        var x = (width - w) / 2;
        var obj = {
            x: x, y: 0,
            width: w - x,
            height: height,
            destWidth: 500,
            destHeight: 400,
            fileType: "jpg",
            success: function success(res) {
                cb(res.tempFilePath);
            },
            fail: function success(res) {
                console.log(res);
            }
        };
        console.log(obj);
        Object.assign(obj, argObj);
        cc.game.canvas.toTempFilePath(obj);
    },
    cleanOldAssets(cb) {
        var wfu = require('WxFileUtils');
        wfu.init();
        console.log('cleanOldAssets path:', wx.env.USER_DATA_PATH)
        var isLogin = false;
        var mainFile = wx.env.USER_DATA_PATH + '/res'
        var isExe = false;
        var remove = () => {
            wfu.removeAllDir(wx.env.USER_DATA_PATH + '/res', (i) => {
                console.log('删除config文件夹成功:' + i)
                isExe = true;
                if (isLogin) {
                    return;
                }
                wfu.removeDir(mainFile, (p, t) => {
                    console.log('检测resources:', t);
                    if (t && !isLogin) {
                        cb();
                        isLogin = true;
                    }
                })
            }, 0)
        }
        setTimeout(remove, 1000)
        setTimeout(() => {
            if (!isExe) {
                cb();
                isLogin = true;
            }
        }, 10000)
    },

    _onShow(option) {
        console.log('切前台', option);
        global.Event.emit('GAMEONSHOW', option);
        this.wxLaunchQuery = option.query;
        this.wxReferrerInfo = option.referrerInfo;
        this.checkNewVersion();
        clearInterval(setTime);
        onShowTime = Date.now();
        if(option.scene == 1101 && !option['referrerInfo'] && !option['shareTicket']){
            Events.emit('backOtherApp')
        }
    },
    _onHide(option) {
        console.log('切后台', option);
        global.Event.emit('GAMEONHIDE', option);
        clearInterval(setTime);
        onShowTime && global.Http.get('/game/gameUser','addOnLineTimeTick',{onLineTimeTick:Date.now()-onShowTime},function(err,res){
            console.log('addOnLineTimeTick:',res);
        })
    },

    changeNetwork(res) {
        console.log('网络：' + res.isConnected, ',类型：' + res.networkType);
        global.Event.emit('CHANGENETWORK', res);
    },

    cleanResource(cb) {
        var fileutil = require('WxFileUtils');
        cc.sys.localStorage.clear();
        var isNoviceRes = cc.sys.localStorage.getItem('isNoviceRes1');
        wx.clearStorage();
        if (isNoviceRes) cc.sys.localStorage.setItem('isNoviceRes1', 'true');
        wx.showToast({ title: '正在清理数据，稍后会自动重启' });
        cc.find('Canvas').destroyAllChildren();
        cc.loader.releaseAll();
        wx.showLoading({ title: '清除资源' });
        fileutil.clearFile(wx.env.USER_DATA_PATH + '/res/raw-assets', (pro) => {
            console.log('删除进度:', pro)
            wx.showLoading({ title: '正在清除:' + Math.floor(pro * 100) + '%' });
        }, () => {
            console.log('删除完成');
            cc.sys.localStorage.clear();
            cb();
        });
    },

    //检测是否有新的版本
    checkNewVersion() {
        if (isChange) return;
        var self = this
        const updateManager = wx.getUpdateManager()
        updateManager.onCheckForUpdate((res) => {
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                isChange = true;
                wx.showModal({
                    showCancel: false,
                    title: '更新提示',
                    content: '检测到新版本，是否更新并重启应用？',
                    success: (res) => {
                        if (res.confirm) {
                                cc.find('Canvas').destroyAllChildren();
                                cc.loader.releaseAll();
                            // self.cleanResource(() => {
                                wx.showLoading({ title: '更新中' });
                                updateManager.onUpdateReady((res) => {
                                    wx.hideLoading();
                                    updateManager.applyUpdate();
                                });
                            // });
                        }
                    }
                });
            }
        });
        updateManager.onUpdateFailed(() => {
            wx.showToast({ title: '新版本下载失败' });
            wx.hideLoading();
        })
    },

    createBanner(options) {
        return wx.createBannerAd(options);
    },

    createRewardedVideoAd(options) {
        return wx.createRewardedVideoAd(options);
    },
    showVideo(id,cb){
        if(!this.videoAd){
            this.videoAd = wx.createRewardedVideoAd({ adUnitId: id });
        }
        let isFirstBack = true;
        this.videoAd.load().then(() =>{
            console.log('广告准备完成')
            this.videoAd.show().then(()=>{
                console.log('广告开始显示')
                cc.game.pause();
            })}
            ).catch(err => console.log(err.errMsg)
        );
        this.videoAd.onError((e) => {
            if (isFirstBack) {
                cb(false)
            }
            cc.sys.localStorage.setItem('lastRewardTime',Date.now());
            cc.sys.localStorage.setItem('lastHasVideo',2);
            console.log('videoAd onError:', e);
        });
        this.videoAd.onClose((res) => {
            if (isFirstBack) {
                cc.game.resume()
                console.log('观看视频回执：', res);
                global.Http.get('/game/gameUser','channelEvent.add',{eventName:'观看视频成功'},function(){
                    
                })
                cb(res.isEnded)
            }
            isFirstBack =false
        });
    }
});

